package com.csdj.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.common.utils.ResponseResult;
import com.csdj.dto.EmpPowerDto;
import com.csdj.pojo.SyEmpareapower;
import com.csdj.pojo.SyEmpareapower;
import com.csdj.service.SyEmpareapowerService;
import com.csdj.mapper.SyEmpareapowerMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
* @author 叶涵
* @description 针对表【sy_empareapower】的数据库操作Service实现
* @createDate 2023-08-24 15:13:39
*/
@Service
public class SyEmpareapowerServiceImpl extends ServiceImpl<SyEmpareapowerMapper, SyEmpareapower>
    implements SyEmpareapowerService{

    /** 设置片区权限保存功能
     * @param empPowerDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult edit(EmpPowerDto empPowerDto) {
        boolean b = false;
        // 判断是单个修改还是批量修改
        if (empPowerDto.getEmpId() != null) {
            // 单个修改
            // 1,需要新增的数据
            ArrayList<Object> addEmpPower = empPowerDto.getAddEmpPower();
            if (addEmpPower != null && addEmpPower.size() > 0) {
                ArrayList<SyEmpareapower> arrayList = new ArrayList<SyEmpareapower>(addEmpPower.size());
                // 取出数据
                for (Object s : addEmpPower) {
                    arrayList.add(JSON.parseObject(JSON.toJSONString(s),SyEmpareapower.class));
                }
                saveBatch(arrayList);
            }
            // 2，需要删除的数据
            ArrayList<Integer> delEmpPower = empPowerDto.getDelEmpPower();
            if (delEmpPower != null && delEmpPower.size()>0) {
                b =  remove(Wrappers.<SyEmpareapower>lambdaQuery().eq(SyEmpareapower::getEmpID,empPowerDto.getEmpId()).in(SyEmpareapower::getAreaID,delEmpPower));
            }
        }else {
            // 批量修改权限
            // 1,拿到所有的员工id
            ArrayList<Integer> empIdList = empPowerDto.getEmpIdList();
            // 2，删除这些员工的所有权限
            b = remove(Wrappers.<SyEmpareapower>lambdaQuery().in(
                    SyEmpareapower::getEmpID,empIdList
            ));
            // 3,拿到新需要新增的
            ArrayList<Object> addEmpPower = empPowerDto.getAddEmpPower();
            ArrayList<SyEmpareapower> arrayList = new ArrayList<SyEmpareapower>();

            // 权限id
            for (Object o : addEmpPower) {
                // 员工id
                for (Integer integer : empIdList) {
                    arrayList.add(new SyEmpareapower(integer, (Integer) o));
                }
            }
            b = saveBatch(arrayList);

        }
        return ResponseResult.okResult(b);
    }
}




